<template>
  <div :class="['breadcrumb-box mask-image', !globalStore.breadcrumbIcon && 'no-icon']">
    <el-breadcrumb :separator-icon="ArrowRight">
      <transition-group name="breadcrumb">
        <template v-if="breadcrumbList?.length > 1">
          <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="item.path">
            <div
              class="el-breadcrumb__inner is-link"
              :class="{ 'item-no-icon': !item.meta.icon }"
              @click="onBreadcrumbClick(item, index)"
            >
              <el-icon v-if="item.meta.title === '首页' && globalStore.breadcrumbIcon" class="breadcrumb-icon">
                <component :is="item.meta.icon"></component>
              </el-icon>
              <span v-if="item.meta.title === '首页' && globalStore.breadcrumbIcon" class="breadcrumb-title">{{
                item.meta.title
              }}</span>
              <el-icon
                style="position: relative; bottom: 1.5px"
                class="breadcrumb-icon"
                v-if="item.meta.icon && item.meta.title != '首页'"
              >
                <i :class="`iconfont ${item.meta.icon}`"></i>
              </el-icon>
              <span
                style="position: relative; bottom: 2.5px"
                v-if="item.meta.icon && item.meta.title != '首页'"
                class="breadcrumb-title"
                >{{ item.meta.title }}</span
              >
            </div>
          </el-breadcrumb-item>
        </template>
        <template v-else>
          <span v-if="show">{{ getTimePeriod() }}</span>
          <span
            v-else-if="breadcrumbList[0].meta.title === '首页'||breadcrumbList[0].meta.title === '账号管理'||breadcrumbList[0].meta.title === '操作日志' && globalStore.breadcrumbIcon && LicenseInfo.running"
            class="breadcrumb-title mg-l-sm"
          >
            运行时间： {{ times }}</span
          >
          <span v-else class="breadcrumb-title mg-l-sm"> {{ breadcrumbList[0].meta.title }}</span>
        </template>
      </transition-group>
    </el-breadcrumb>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted } from "vue";
import { HOME_URL } from "@/config";
import { useRoute, useRouter } from "vue-router";
import { ArrowRight } from "@element-plus/icons-vue";
import { useAuthStore } from "@/stores/modules/auth";
import { useGlobalStore } from "@/stores/modules/global";
const role = localStorage.getItem("role");
const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const globalStore = useGlobalStore();

const breadcrumbList = computed(() => {
  let breadcrumbData = authStore.breadcrumbListGet[route.matched[route.matched.length - 1].path] ?? [];
  // 🙅‍♀️不需要首页面包屑可删除以下判断
  if (breadcrumbData[0].path !== HOME_URL) {
    breadcrumbData = [{ path: HOME_URL, meta: { icon: "HomeFilled", title: "首页" } }, ...breadcrumbData];
  }
  return breadcrumbData;
});

// Click Breadcrumb
const onBreadcrumbClick = (item: Menu.MenuOptions, index: number) => {
  if (index !== breadcrumbList.value.length - 1) router.push(item.path);
};

function getTimePeriod(date) {
  // 如果未提供日期参数，则使用当前时间
  const currentDate = date || new Date();
  // 获取小时数（0-23）
  const hours = currentDate.getHours();

  // 时间段划分：
  // 早上：5点-11点
  // 中午：11点-13点
  // 下午：13点-18点
  // 晚上：18点-次日5点
  if (hours >= 5 && hours < 11) {
    return "早上好！";
  } else if (hours >= 11 && hours < 13) {
    return "中午好！";
  } else if (hours >= 13 && hours < 18) {
    return "下午好！";
  } else {
    return "晚上好！";
  }
}

import { ref } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { cfg_softcheck, licenseList } from "@/api/modules/system/params";
import { cfgAppstate } from "@/api/modules/home";

const times = ref("");
const show = ref(true);
setTimeout(() => {
  show.value = !show.value;
}, 2000);

function getFormattedLocalTime() {
  const now = new Date();

  // 提取时间维度（注意：getMonth() 从 0 开始，需 +1；getDate() 是当月日期，无需处理）
  const year = now.getFullYear(); // 年（如 2024）
  const month = now.getMonth() + 1; // 月（0-11 → 1-12）
  const day = now.getDate(); // 日（1-31）
  const hours = now.getHours(); // 时（0-23，24小时制）
  const minutes = now.getMinutes(); // 分（0-59）
  const seconds = now.getSeconds(); // 秒（0-59）

  // 工具函数：个位数补 0（如 5 → "05"，12 → "12"）
  const padZero = num => num.toString().padStart(2, "0");

  // 拼接成指定格式
  times.value = `${year}-${padZero(month)}-${padZero(day)} ${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
}

let timer = setInterval(() => {
  getFormattedLocalTime();
}, 1000);
onUnmounted(() => {
  clearInterval(timer);
  timer = null;
});

let LicenseInfoStr = localStorage.getItem("LicenseInfo");
const LicenseInfo = ref({
  license: "",
  version: "",
  isLicence: false,
  running: false
});

async function getCfg() {
  if (!useUserStore().userInfo.name) return;
  const res1 = await licenseList();
  const res2 = await cfgAppstate();
  const res3 = await cfg_softcheck();
  console.log("res2=============", res2);
  // useUserStore.setLicenseInfo({
  //   isLicence: res1.result.data && res1.result.data.length,
  //   license: res1.result.data[0][1] == 1 ? "测试版" : "正式版"
  // });
  localStorage.setItem(
    "LicenseInfo",
    JSON.stringify({
      isLicence: Boolean(res1.result.data && res1.result.data.length),
      license: res1.result.data[0][1],
      version: res3.version,
      licenseTime: res1.result.data[0][6],
      day: res1.result.data[0][4],
      running: res2.code > 0
    })
  );
  LicenseInfo.value = {
    isLicence: Boolean(res1.result.data && res1.result.data.length),
    license: res1.result.data[0][1],
    version: res3.version,
    licenseTime: res1.result.data[0][6],
    day: res1.result.data[0][4],
    running: res2.code > 0
  };
  console.log("LicenseInfoStr=", LicenseInfo.value);
}

setTimeout(() => {
  getCfg();
}, 4000);
</script>

<style scoped lang="scss">
.breadcrumb-box {
  display: flex;
  align-items: center;
  overflow: hidden;

  .el-breadcrumb {
    white-space: nowrap;

    .el-breadcrumb__item {
      position: relative;
      display: inline-block;
      float: none;

      .item-no-icon {
        transform: translateY(-3px);
      }

      .el-breadcrumb__inner {
        display: inline-flex;

        &.is-link {
          color: var(--el-header-text-color);

          &:hover {
            color: var(--el-color-primary);
          }
        }

        .breadcrumb-icon {
          margin-top: 1px;
          margin-right: 6px;
          font-size: 16px;
        }

        .breadcrumb-title {
          margin-top: 2px;
        }
      }

      &:last-child .el-breadcrumb__inner,
      &:last-child .el-breadcrumb__inner:hover {
        color: var(--el-header-text-color-regular);
      }

      :deep(.el-breadcrumb__separator) {
        transform: translateY(-1px);
      }
    }
  }
}

.no-icon {
  .el-breadcrumb {
    .el-breadcrumb__item {
      top: -2px;

      :deep(.el-breadcrumb__separator) {
        top: 4px;
      }

      .item-no-icon {
        transform: translateY(0);
      }
    }
  }
}
</style>
